﻿using System;
using System.Windows.Input;
using System.Windows;
using MDCAdminTool.Controls;

namespace MDCAdminTool.Commands
{
    public class AddDataCacheItem : CommandBinding
    {
        public AddDataCacheItem()
        {
            Command = Application.Current.Resources["AddDataCacheItemCommand"] as ICommand;
            CanExecute += OnCanExecute;
            Executed   += OnExecuted;
        }

        protected void OnExecuted( object sender , ExecutedRoutedEventArgs e )
        {
            var cache = e.Parameter as MdcCache;
            CacheRegion cr = null;

            if ( cache == null )
            {
                cr = e.Parameter as CacheRegion;

                if ( cr != null )
                    cache = cr.Parent as MdcCache;
            }

            if ( cache != null )
            {
                try
                {
                    var win = new AddDataCacheItemWin();
                    win.ShowDialog();
                    if ( win.IsSave )
                    {
                        if ( !string.IsNullOrEmpty( win.Key ) && 
                         !string.IsNullOrEmpty( win.Value ) )
                        {
                            var client = CacheClientFactory.GetCache( cache );
                            if ( client != null )
                                client.Add( win.Key , win.Value );
                        }
                        else if ( !string.IsNullOrEmpty( win.Number ) )
                        {
                            var num = Convert.ToInt32( win.Number );
                            var client = CacheClientFactory.GetCache( cache );
                            if ( client != null )
                            {
                                for ( int i = 0 ; i < num ; i++ )
                                {
                                    client.Add( Guid.NewGuid().ToString() , i );
                                }
                            }
                        }
                    }
                    win.Close();
                }
                catch {}
            }
        }
        protected void OnCanExecute( object sender , CanExecuteRoutedEventArgs e )
        {
            e.CanExecute = true;
        }
    }
}
